#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "common.h"

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 9999
#define BUFFER_SIZE 1024

#define TCPCLIENT_RECV_TASKNAME         "tcp_recv_client"
#define TCPCLIENT_WRITE_TASKNAME        "tcp_write_client"
#define WORK_PROCESS_TASKNAME           "work_process"



static void *client_recv_loop(void * param)
{
    char buf[BUFFER_SIZE];
    char buff[BUFFER_SIZE];
    printf("client_recv_loop sockfd is [%d]\n",((client_info_p )param)->sockfd);
    while (1)
    {
        printf("Enter message: ");
        fgets(buf, BUFFER_SIZE, stdin);
        memcpy(((client_info_p )param)->buf, buf, strlen(buf));
        if (strcmp(buf, "exit\n") == 0) break;
    }
    
    printf("client_recv_loop exit!\n");
    close(((client_info_p )param)->sockfd);
    return NULL;
}

static void *client_write_loop(void * param)
{
    // char buf[BUFFER_SIZE] = "hello client_write_loop";
    while (1)
    {
        if (((client_info_p )param)->buf[0] != '\0')
        {
            if (write(((client_info_p )param)->sockfd, ((client_info_p )param)->buf, strlen(((client_info_p )param)->buf)) < 0) {
                perror("write error");
                exit(EXIT_FAILURE);
            }
            else
            {
                printf("client_write_loop send message: %s\n", ((client_info_p )param)->buf);
                bzero(((client_info_p )param)->buf, BUFFER_SIZE);
            }
        }
        else
        {
            sleep(1);
        }
    }

    printf("client_write_loop exit!\n");
    close(((client_info_p )param)->sockfd);
    return NULL;
}


int main(int argc, const char** argv) {
    int sockfd;
    struct sockaddr_in servaddr;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERVER_PORT);

    if (inet_pton(AF_INET, SERVER_IP, &servaddr.sin_addr) <= 0) {
        perror("inet_pton error");
        exit(EXIT_FAILURE);
    }

    if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("connect error");
        exit(EXIT_FAILURE);
    }

    client_info_t client_info = {sockfd,0};

    create_task(TCPCLIENT_RECV_TASKNAME, client_recv_loop, &client_info);
    create_task(TCPCLIENT_WRITE_TASKNAME, client_write_loop, &client_info);

    while (1) {
        sleep(1);
    }

    return 0;
}